package com.tusuo.stds.ui.resetpassword;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.util.IntentUtils;
import com.tusuo.stds.util.Utils;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import okhttp3.Headers;
import retrofit2.adapter.rxjava.Result;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(ResetPasswordPresenter.class)
class ResetPasswordPresenter extends MvpBasePresenter<ResetPasswordView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscription subscriptionUpdateCountdown;
    private Handler handlerShowErrMsg;
    private boolean isWaiting;
    private Subscriber<ApiResult> mGetCaptchaSubscriber = null;
    private Subscriber<ApiResult> mSetPasswordSubscriber = null;

    ResetPasswordPresenter(Context context) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        handlerShowErrMsg = new Handler();
        isWaiting = false;

        Injector.initResetPasswordPresenterComponent().inject(this);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (handlerShowErrMsg != null) {
            handlerShowErrMsg.removeCallbacksAndMessages(null);
        }
        if (subscriptionUpdateCountdown != null) {
            subscriptionUpdateCountdown.unsubscribe();
        }
        if (mGetCaptchaSubscriber != null) {
            mGetCaptchaSubscriber.unsubscribe();
            mGetCaptchaSubscriber = null;
        }
        if (mSetPasswordSubscriber != null) {
            mSetPasswordSubscriber.unsubscribe();
            mSetPasswordSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    private Runnable showSloganRunnable = new Runnable() {
        @Override
        public void run() {
            if (getView() != null) {
                getView().showSlogan();
            }
        }
    };

    void showErrMsg(String text) {
        if (getView() != null) {
            getView().showErrMsg(text);
            handlerShowErrMsg.postDelayed(showSloganRunnable, 3000);
        }
    }

    void getCaptcha(String mobileNo) {
        mGetCaptchaSubscriber = new GetCaptchaSubscriber();
        mApiHelper.getCaptcha(mGetCaptchaSubscriber, mobileNo);

        if (getView() != null) {
            getView().setSmsText(mContext.getString(R.string.reset_password_sms, mobileNo));

            subscriptionUpdateCountdown = updateCountdown()
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            getView().setCaptchaBtnEnabled(false);
                            isWaiting = true;
                        }
                    })
                    .subscribe(new Subscriber<Integer>() {
                        @Override
                        public void onCompleted() {
                            getView().setCaptchaBtnText(mContext.getString(R.string.btn_captcha));
                            getView().setCaptchaBtnEnabled(true);
                            isWaiting = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(Integer integer) {
                            getView().setCaptchaBtnText(mContext.getString(R.string.btn_wait_captcha, integer));
                        }
                    });
        }
    }

    private Observable<Integer> updateCountdown() {
        final int countTime = 60;

        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<Long, Integer>() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime+1);
    }

    void allowGoBack() {
        isWaiting = false;
        if (subscriptionUpdateCountdown != null) {
            subscriptionUpdateCountdown.unsubscribe();
        }
    }

    boolean canGoBack() {
        return !isWaiting;
    }

    void setPassword(String mobileNo, String password, String captcha) {
        Subscriber<ApiResult> mSetPasswordSubscriber = new SetPasswordSubscriber();
        mApiHelper.setPassword(mSetPasswordSubscriber, mobileNo, password, captcha);
    }

    private class GetCaptchaSubscriber extends Subscriber<ApiResult> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            showErrMsg(mErrMsgServer);
        }

        @Override
        public void onNext(ApiResult result) {
            if (!result.checkState(mContext)) {
                showErrMsg(result.ErrorMessage);
            }
        }
    }

    private class SetPasswordSubscriber extends Subscriber<ApiResult> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            showErrMsg(mErrMsgServer);
        }

        @Override
        public void onNext(ApiResult result) {
            if (result.checkState(mContext)) {
                Utils.UI.showToastShort("密码重置成功！请重新登录");
                IntentUtils.toLogin(mContext);
            } else {
                showErrMsg(result.ErrorMessage);
            }
        }
    }
}
